<template>
  <div v-loading="loading">
    <el-card>
      <template #header>
        <div>
          <span>搜索</span>
        </div>
      </template>
      <el-form inline>
        <el-form-item label="文件名">
          <el-input v-model="searchCond.name" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="searchCond.note" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker type="daterange" value-format="YYYY-MM-DD" v-model="searchCond.date" range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="作者">
          <el-input v-model="searchCond.author" />
        </el-form-item>
        <!--<el-form-item label="系列">
          <el-select filterable default-first-option style="width: 200px" multiple v-model="searchCond.series" placeholder="选择系列">
            <el-option v-for="seriesItem in allSeries" :key="seriesItem.Pk" :label="seriesItem.SeriesName" :value="seriesItem.Pk" />
          </el-select>
        </el-form-item>-->
        <el-form-item label="系列">
          <el-input v-model="searchCond.seriesname" />
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 10px" />
    <el-empty v-if="pageList.length === 0" description="找不到数据" />
    <el-space wrap>
      <el-card class="img-card" v-for="item in pageList" :key="item.Pk" :body-style="{ padding: '0px', marginBottom: '1px' }">
        <el-image :src="'api/Image/Thumbnail?pk=' + item?.Pk" class="img-div" :preview-src-list="['api/Image/Preview?pk=' + item?.Pk]" />
        <div style="padding: 5px 10px">
          <div class="img-note">{{ item.ImageName }}</div>
          <div class="img-note" style="font-size: small">
            所需分数： <span style="font-weight: bold">{{ item.Price }}</span>
          </div>
          <div class="img-note" style="font-size: small">
            系列: <span style="font-weight: bold">{{ item.SeriesName }}</span>
          </div>
          <div class="img-note" style="font-size: small">
            <span style="font-weight: bold">{{ item.Author }}</span>
            上传于{{ item.CreateDate?.substring(0, 10) }}
          </div>
          <div class="img-note" v-if="item.Heat! > 0" style="font-size: small">
            <el-popover :width="300">
              <template #reference>
                <span style="font-weight: bold">{{ item.LastDownloader }}</span>
              </template>
              <el-tag style="margin: 2px 2px" v-for="i in item.AllDownloaders" :key="i">{{ i }}</el-tag>
            </el-popover>
            等{{ item.Heat }}人下载过
          </div>
          <div style="margin-top: 10px">
            <el-button size="small" @click="download(item)">下载</el-button>
          </div>
        </div>
      </el-card>
    </el-space>
    <div style="padding: 10px 10px; width: 100%; text-align: center" v-if="more"><el-button @click="fetchData" style="width: 80%" size="large">加载更多</el-button></div>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { list } from '@/api/image';
import type { ImageModel } from '@/model/imagemodel';
import { useUserStore } from '@/stores/userInfo';
import { ElMessage, ElMessageBox } from 'element-plus';
import { listImg } from '@/api/downloadHistory';
const more = ref(false);
const loading = ref(false);
const pageList = ref<ImageModel[]>([]);
const onResize = () => {
  colCount.value = Math.floor(window.innerWidth / 330);
};

const searchCond = ref({ name: '', note: '', date: [], author: '', series: [], seriesname: '' });
const colCount = ref(1);
const pageIndex = ref(1);
const pageSize = ref(10);
const download = (item: ImageModel) => {
  const user = useUserStore();
  if (item.Creator === user.user?.UserId) {
    download2(item.Pk, item.ImageName, user.token);
    return;
  }
  ElMessageBox.confirm('下载需要' + item.Price + '积分，确认继续?(同一用户多次下载不会重复计算)', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    download2(item.Pk, item.ImageName, user.token);
  });
};
const download2 = (pk?: string, name?: string, token?: string) => {
  const url = 'api/Image/Download?pk=' + pk + '&Authorization=' + token;
  const a = document.createElement('a');
  a.setAttribute('target', '_blank');
  a.setAttribute('download', name!);
  a.setAttribute('href', url);
  a.click();
};
const search = () => {
  pageIndex.value = 1;
  pageList.value = [];
  fetchData();
};
const fetchData = () => {
  const cond: any = { pageIndex: pageIndex.value, pageSize: pageSize.value, S_Publish: 'eq(Y)' };
  if (searchCond.value.series && searchCond.value.series.length > 0) {
    let p = '';
    searchCond.value.series.forEach((r) => {
      p += r + ',';
    });
    p = p.substring(0, p.length - 1);
    cond.S_Series = 'in(' + p + ')';
  }
  if (searchCond.value.author) {
    cond.S_Author = 'lk(' + searchCond.value.author + ')';
  }
  if (searchCond.value.seriesname) {
    cond.S_SeriesName = 'lk(' + searchCond.value.seriesname + ')';
  }
  if (searchCond.value.name) {
    cond.S_ImageName = 'lk(' + searchCond.value.name + ')';
  }
  if (searchCond.value.note) {
    cond.S_Note = 'lk(' + searchCond.value.note + ')';
  }
  if (searchCond.value.date.length >= 1) {
    cond.S_CreateDate_1 = 'ge(' + searchCond.value.date[0] + ' 00:00:00)';
  }
  if (searchCond.value.date.length === 2) {
    cond.S_CreateDate_2 = 'le(' + searchCond.value.date[1] + ' 23:59:59)';
  }
  loading.value = true;
  list(cond)
    .then((r) => {
      r.Data?.forEach((r) => {
        if (!pageList.value.find((s) => s.Pk === r.Pk)) {
          pageList.value.push(r);
          fillLastDownLoader();
        }
      });
      if (r.TotalCount! <= pageList.value.length) {
        more.value = false;
        ElMessage.info('加载完成');
      } else {
        more.value = true;
      }
      loading.value = false;
      pageIndex.value += 1;
    })
    .catch(() => {
      loading.value = false;
    });
};
onMounted(() => {
  onResize();
  window.addEventListener('resize', onResize);
  fetchData();
});
const fillLastDownLoader = () => {
  pageList.value.forEach((item) => {
    if (!item.LastDownloader) {
      listImg(item.Pk!).then((r) => {
        item.AllDownloaders = [];
        const allls = r.Data?.sort((a, b) => b.CreateDate!.localeCompare(a.CreateDate!));
        allls?.forEach((i) => {
          item.AllDownloaders?.push(i.Creator!._v2!);
        });
        const lastls = allls?.slice(0, 4);
        if (lastls!.length > 0) {
          let str = '';
          lastls?.forEach((i) => {
            str += i.Creator?._v2 + ',';
          });
          item.LastDownloader = str.slice(0, str.length - 1);
        }
      });
    }
  });
};
</script>
<style scoped>
.img-card {
  width: 290px;
  height: 380px;
}
.img-div {
  width: 100%;
  height: 200px;
}
.img-note {
  margin: 3px;
}
</style>
